﻿//------------------------------------------------------------
// Game Framework
// Copyright © 2013-2021 Jiang Yin. All rights reserved.
// Homepage: https://gameframework.cn/
// Feedback: mailto:ellan@gameframework.cn
//------------------------------------------------------------

using GameFramework;
using GameFramework.Event;
using GameFramework.Resource;
using SuperScrollView;
using System;
using System.Collections.Generic;
using UGFExtensions.SpriteCollection;
using UnityEngine;
using UnityEngine.UI;
using UnityGameFramework.Runtime;
using DG.Tweening;

namespace Adventure
{
    public class RegisterForm : UGuiForm
    {
        private InputField userInput;
        private InputField passwordInput;
        private InputField toPasswordInput;
        private UIButton registerButton;
        private UIButton tipButton;
        private UIButton loginButton;
        private UIButton headButton;

        private Image headValue;
        private RectTransform tipPanel;

        private RectTransform headScrollView;

        private LoopListView2 mScrollView;
        private ScrollRect mScrollRect;

        private List<RegisterHeadData> datas;

        private const int mItemCount = 3;
        private int mCount
        {
            get
            {
                return datas.Count % mItemCount > 0 ? datas.Count / mItemCount + 1 : datas.Count / mItemCount;
            }
        }

        protected override void OnInit(object userData)
        {
            base.OnInit(userData);

            userInput = transform.FindTransform<InputField>("UserInputField");
            passwordInput = transform.FindTransform<InputField>("PasswordInputField");
            toPasswordInput = transform.FindTransform<InputField>("ToPasswordInputField");

            registerButton = transform.FindTransform<UIButton>("RegisterButton");
            tipButton = transform.FindTransform<UIButton>("TipButton");
            loginButton = transform.FindTransform<UIButton>("LoginButton");
            headButton = transform.FindTransform<UIButton>("HeadButton");

            headValue = transform.FindTransform<Image>("HeadValue");

            tipPanel = transform.FindTransform<RectTransform>("TipPanel");
            headScrollView = transform.FindTransform<RectTransform>("HeadScrollView");

            mScrollView = transform.FindTransform<LoopListView2>("HeadScrollView");

            datas = RegisterHeadData.Initialize();
            mScrollView.InitListView(mCount, GetScrollViewUpdate);

            mScrollView.SupportScrollBar = false;
            mScrollView.ItemSnapEnable = false;

            mScrollRect = mScrollView.GetComponent<ScrollRect>();
            mScrollRect.horizontal = false;
            mScrollRect.vertical = true;
            mScrollRect.horizontalScrollbar = null;
            mScrollRect.verticalScrollbar = null;
        }
        protected override void OnOpen(object userData)
        {
            base.OnOpen(userData);

            UIEventTrigger.Get(registerButton).onClick = OnRegisterButtonClick;
            UIEventTrigger.Get(loginButton).onClick = OnLoginButtonClick;
            UIEventTrigger.Get(tipButton).onDown = OnShowTipButtonClick;
            UIEventTrigger.Get(tipButton).onUp = OnHideTipButtonClick;
            UIEventTrigger.Get(headButton).onClick = OnHeadButtonClick;
            GameEntry.Event.Subscribe(RegisterHeadEventArgs.EventId, OnReception);

            userInput.text = string.Empty;
            passwordInput.text = string.Empty;
            toPasswordInput.text = string.Empty;

            //暂且先不弄默认头像
            headValue.sprite = null;
            mScrollView.MovePanelToItemIndex(0,0);
            headScrollView.DOAnchorPos3DX(500, 0f).SetEase(Ease.Linear);

            tipPanel.gameObject.SetActive(false);
        }

        private void OnHideTipButtonClick(GameObject go)
        {
            tipPanel.gameObject.SetActive(false);
        }

        private void OnShowTipButtonClick(GameObject go)
        {
            tipPanel.Find("TipText").GetComponent<Text>().text = GameEntry.Localization.GetString("Register.TipContent", "\n", "\n", "\n");
            tipPanel.gameObject.SetActive(true);
        }

        private void OnReception(object sender, GameEventArgs e)
        {
            RegisterHeadEventArgs n = (RegisterHeadEventArgs)e;
            headValue.SetSprite(Constant.SpriteCollectionPath,AssetUtility.GetUIDynamicSrpiteAsset(n.Data.name));          
        }

        protected override void OnClose(bool isShutdown, object userData)
        {
            base.OnClose(isShutdown, userData);

            UIEventTrigger.Get(registerButton).onClick = null;
            UIEventTrigger.Get(headButton).onClick = null;
            UIEventTrigger.Get(tipButton).onDown = null;
            UIEventTrigger.Get(tipButton).onUp = null;
            GameEntry.Event.Unsubscribe(RegisterHeadEventArgs.EventId, OnReception);
     
        }
        private void OnRegisterButtonClick(GameObject go)
        {
            PlayUISound(10000);

            if (GameEntry.UI.HasUIForm(UIFormId.TipForm)) return;

            GameEntry.ArchiveData.SetUserLoadPath(userInput.text);

          
            bool arg1 = userInput.text != string.Empty && passwordInput.text != string.Empty;//输入内容不能是空
            bool arg2 = toPasswordInput.text == passwordInput.text;//密码和确认密码需要一致
            bool agr3 = headValue.sprite != null;//默认头像不能是空
            bool arg4 = !IOHelper.IsFileExists(GameEntry.ArchiveData.GetFullFilePath());//禁止重复账号

            //判断条件在这里依次累加

            if (arg1 && arg2 && agr3 && arg4)
            {
                //注册成功
                GameEntry.ArchiveData.Data.player.User = userInput.text;
                GameEntry.ArchiveData.Data.player.Password = passwordInput.text;
                GameEntry.ArchiveData.Data.player.HeadString = headValue.sprite.name;

                //清除数据的时候可以重复注册一下就好了
                GameEntry.ArchiveData.Data.Gold = 100;
                GameEntry.ArchiveData.Data.KillCount = 0;
                GameEntry.ArchiveData.Data.BackpackerCount = 0;
                GameEntry.ArchiveData.Data.ShopCount = 0;
                GameEntry.ArchiveData.Data.player.PlayerId =1;
                GameEntry.ArchiveData.Data.player.CurrentEXP =0;
                GameEntry.ArchiveData.Data.player.CurrentHP = GameEntry.DataTable.GetDRPlayer(GameEntry.ArchiveData.Data.player.PlayerId).MaxHP;

                GameEntry.ArchiveData.Save();

                string content = GameEntry.Localization.GetString("Tip.RegisterSucceed");
                int colorCode = 2;
                GameEntry.UI.OpenUIForm(UIFormId.TipForm, Tuple.Create(content, colorCode));
            }
            else
            {
                //注册失败，看情况是否需要区分错误
                string content = GameEntry.Localization.GetString("Tip.RegisterErro");
                int colorCode = 1;
                GameEntry.UI.OpenUIForm(UIFormId.TipForm, Tuple.Create(content, colorCode));
            }

            GameEntry.TimerComponent.AddOnceTimer(1000, () => { GameEntry.UI.CloseUIForm(GameEntry.UI.GetUIForm(UIFormId.TipForm)); });
        }
        private void OnLoginButtonClick(GameObject go)
        {
            PlayUISound(10000);

            GameEntry.UI.OpenUIForm(UIFormId.LoginForm);
            Close();
        } 
        private void OnHeadButtonClick(GameObject go)
        {
            PlayUISound(10000);

            if (headScrollView.anchoredPosition.x==500)
            {
                headScrollView.DOAnchorPos3DX(-100, 0.3f).SetEase(Ease.Linear);
            }
            else
            {
                headScrollView.DOAnchorPos3DX(500, 0.3f).SetEase(Ease.Linear);
            }
          
            //打开头像滑动列表
        }
        private LoopListViewItem2 GetScrollViewUpdate(LoopListView2 listView, int index)
        {
            if (index < 0 || index >= datas.Count) return null;

            var Item2 = listView.NewListViewItem("Itemline");

            RegisterHeadItemline scriptItemLine = Item2.gameObject.GetComponent<RegisterHeadItemline>();
            if (scriptItemLine == null) scriptItemLine = Item2.gameObject.AddComponent<RegisterHeadItemline>();

            if (Item2.IsInitHandlerCalled == false)
            {
                Item2.IsInitHandlerCalled = true;
                scriptItemLine.Init();
            }
            for (int i = 0; i < mItemCount; ++i)
            {
                int itemIndex = index * mItemCount + i;
                if (itemIndex >= datas.Count)
                {
                    scriptItemLine.objs[i].gameObject.SetActive(false);
                    continue;
                }

                if (datas != null)
                {
                    scriptItemLine.objs[i].SetActive(true);

                    scriptItemLine.objs[i].GetComponent<RegisterHeadItem>().SetItemData(datas[itemIndex], itemIndex);
                }
                else
                {
                    scriptItemLine.objs[i].gameObject.SetActive(false);
                }
            }
            return Item2;
        }

    }

    public class RegisterHeadData
    {
        public string name;
   
        private const int  headCount=46;
        public static List<RegisterHeadData> Initialize()
        {
            var vo = new List<RegisterHeadData>();
     
            for (int i = 0; i < headCount; i++)
            {
                vo.Add(new RegisterHeadData() { name = "Head_" + i });
            }

            return vo;
        }
    }

    public class RegisterHeadItemline : MonoBehaviour
    {
        public List<GameObject> objs;

        public void Init()
        {
            if (objs == null)
            {
                objs = new List<GameObject>();
            }
            for (int i = 0; i < transform.childCount; i++)
            {
                objs.Add(transform.GetChild(i).gameObject);
                transform.GetChild(i).gameObject.AddComponent<RegisterHeadItem>();
            }

            foreach (GameObject item in objs)
            {
                item.GetComponent<RegisterHeadItem>().Init();
            }
        }
    }
  
    public class RegisterHeadItem : MonoBehaviour
    {
        public Image headImg;
        public UIButton headButton;

        public RegisterHeadData data;
        public void Init()
        {
            headImg = transform.FindTransform<Image>("ValueImage");
            headButton = GetComponent<UIButton>();
            data = new RegisterHeadData();

            headButton.onClick.AddListener(() =>
            {
                //发送出去
                GameEntry.Event.Fire(this, RegisterHeadEventArgs.Create(data));

                GameEntry.Sound.PlayUISound(10001);
            });
        }

        public void SetItemData(object arg, int index)
        {         
            data.name = ((RegisterHeadData)arg).name;

            headImg.SetSprite(Constant.SpriteCollectionPath, AssetUtility.GetUIDynamicSrpiteAsset(data.name));   
        }
    }
}
